import { router, addRouters } from '@/router/index.js'
import { getToken } from '@/composables/auth.js'
import { toast, showFullLoading, hideFullLoading } from '@/composables/util.js'
import store from './store'
let hasGetInfo = false

router.beforeEach(async (to, from, next) => {
  const token = getToken()
  showFullLoading()
  if (!token && to.path != '/login') {
    toast('Please log in again !', 'error')
    next({ path: '/login' })
  }

  if (token && to.path == '/login') {
    toast('Do not Please log in again!', 'error')
    next({ path: from.path ? from.path : '/' })
  }
  let hasNewRoutes = false

  if (token && !hasGetInfo) {
    let { data } = await store.dispatch('getinfo')
    hasGetInfo = true
    hasNewRoutes = addRouters(data.menus)
  }
  let title = to.meta.title ? to.meta.title : ''
  document.title = title
  hasNewRoutes ? next(to.fullPath) : next()
})

router.afterEach((to, from) => hideFullLoading())
